package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.entity.CmsSuppliersTempEntity;
import com.yuanda.erp9.syn.enums.*;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.poi.WaldomCsvData;
import com.yuanda.erp9.syn.pojo.BatchParamPojo;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.pojo.CmsPricesPojo;
import com.yuanda.erp9.syn.service.erp9.WaldomDataImportService;
import com.yuanda.erp9.syn.util.CsvReadUtils;
import com.yuanda.erp9.syn.util.DateUtils;
import com.yuanda.erp9.syn.util.EasyExcelUtils;
import com.yuanda.erp9.syn.util.RateCalculateUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

/**
 * @desc   Waldom数据导入的实现类
 * @author linuo
 * @time   2022年11月30日16:29:53
 */
@Service
@Slf4j
public class WaldomDataImportServiceImpl extends CsvSaveImpl implements WaldomDataImportService {
    /** 供应商名称 */
    private static final String SUPPLIER = "北京英赛尔科技有限公司";

    /** 供应商id */
    private static final String SUPPLIER_ID = "US000002389";

    /**
     * 组装CmsGoodsPojo数据
     * @param topicUpdateLogId 系统主体更新日志记录表id
     * @param filePath 文件路径
     */
    @Override
    public String importCmsGoodsPojo(Long topicUpdateLogId, String filePath) {
        Integer supplierId = suppliersCache.get(SUPPLIER);
        if(supplierId == null){
            // 插入供应商数据
            CmsSuppliersTempEntity cmsSuppliersTempEntity = new CmsSuppliersTempEntity();
            cmsSuppliersTempEntity.setSupplierUs(SUPPLIER_ID);
            cmsSuppliersTempEntity.setName(SUPPLIER);
            cmsSuppliersTempEntity.setTag(0);
            int insert = cmsSuppliersTempMapper.insert(cmsSuppliersTempEntity);
            if(insert > 0){
                supplierId = cmsSuppliersTempEntity.getSupplierid();
            }
        }

        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, null, SourceEnum.DATA_PACKAGE.getCode());

        try {
            // 读取csv数据
            List<String[]> strings = CsvReadUtils.parseCSV(filePath);
            if(strings != null && strings.size() > 0){
                if(topicUpdateLogId != null){
                    // 插入系统主体更新数量日志记录表数据
                    Integer integer = cmsTopicUpdateSumLogService.insertBySum((long) strings.size(), topicUpdateLogId);
                    if(integer > 0){
                        log.info("插入系统主体更新数量日志记录表数据成功");
                    }
                }

                log.info("创建Waldom数据导入任务开始");
                for (int i = 0; i < strings.size(); i++) {
                    String[] string = strings.get(i);
                    WaldomCsvData waldomCsvData = WaldomCsvData.toWaldomCsvDataFormat(string, i);
                    if(Strings.isNullOrEmpty(waldomCsvData.getManufacturerName())){
                        continue;
                    }

                    if (string.length == 36) {
                        try {
                            CmsGoodsPojo cmsGoodsPojo = packageCmsGoodsPojo(waldomCsvData, supplierId);
                            if(cmsGoodsPojo != null){
                                objectMaster.add(cmsGoodsPojo);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }finally {
            // 退出标志
            objectMaster.isBegin = false;
        }
        log.info("创建Waldom数据导入任务结束");
        return "ok";
    }

    /**
     * Waldom数据组装
     * @param waldomCsvData Waldom数据解析
     */
    private CmsGoodsPojo packageCmsGoodsPojo(WaldomCsvData waldomCsvData, Integer supplierId) {
        CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();

        cmsGoodsEntity.setAdminid(0);
        cmsGoodsEntity.setTenantsid(0);
        cmsGoodsEntity.setSupplier(supplierId);

        // 产品唯一标识
        String sign = SUPPLIER_ID + waldomCsvData.getRow();
        String incodes = EasyExcelUtils.getIncodes(sign, SUPPLIER_ID, "", "", "", "", "", cmsGoodsEntity.getSupplier());
        cmsGoodsEntity.setIncodes(incodes);
        cmsGoodsEntity.setGoodid(incodes);

        cmsGoodsEntity.setClassifyid(0);
        cmsGoodsEntity.setImg("");
        cmsGoodsEntity.setType(0);
        cmsGoodsEntity.setStatus(1);
        cmsGoodsEntity.setStatusMsg(null);
        cmsGoodsEntity.setDataType(1);

        // 名称
        String partNumber = waldomCsvData.getPartNumber();
        cmsGoodsEntity.setModel(partNumber);

        // 处理品牌信息，缓存中没有当前品牌时添加信息到数据库和缓存中
        String manufacturer = waldomCsvData.getManufacturerName();
        Integer i = brandCache.get(manufacturer);
        if (i == null) {
            // 插入品牌数据
            Integer brandId = insertBrand(manufacturer);
            cmsGoodsEntity.setBrand(brandId);
        }else{
            cmsGoodsEntity.setBrand(i);
        }

        cmsGoodsEntity.setIsSampleApply(0);
        cmsGoodsEntity.setOriginalPrice(BigDecimal.ZERO);
        cmsGoodsEntity.setPurchasePrice(BigDecimal.ZERO);

        // 库存
        String inStockEMEA = waldomCsvData.getInStockEMEA();
        String inStockUSA = waldomCsvData.getInStockUSA();

        if(!Strings.isNullOrEmpty(inStockEMEA) && Double.valueOf(inStockEMEA).intValue() > 0){
            // 库存
            cmsGoodsEntity.setRepertory(Integer.valueOf(inStockEMEA));

            // 库存所在地
            cmsGoodsEntity.setRepertoryArea("欧洲");

            cmsGoodsEntity.setDomesticDate("10-12工作日");
            cmsGoodsEntity.setHongkongDate("10-12工作日");

            // 批次号
            List<String> list = new ArrayList<>();
            list.add("EMEA");
            String batch = createBatchData(waldomCsvData.getDateCode(), list);
            cmsGoodsEntity.setBatch(batch);

            return createCmsGoodsEntityData(waldomCsvData, cmsGoodsEntity);
        }

        if(!Strings.isNullOrEmpty(inStockUSA) && Double.valueOf(inStockUSA).intValue() > 0){
            // 库存
            cmsGoodsEntity.setRepertory(Integer.valueOf(inStockUSA));

            // 库存所在地
            cmsGoodsEntity.setRepertoryArea("美国");

            cmsGoodsEntity.setDomesticDate("7-10工作日");
            cmsGoodsEntity.setHongkongDate("5-8工作日");

            // 批次号
            List<String> list = new ArrayList<>();
            list.add("US");
            list.add("USA");
            String batch = createBatchData(waldomCsvData.getDateCode(), list);
            cmsGoodsEntity.setBatch(batch);

            return createCmsGoodsEntityData(waldomCsvData, cmsGoodsEntity);
        }

        return null;
    }

    /**
     * 组装商品表数据
     * @param cmsGoodsEntity 商品表
     * @param waldomCsvData Waldom数据解析
     */
    private CmsGoodsPojo createCmsGoodsEntityData(WaldomCsvData waldomCsvData, CmsGoodsEntity cmsGoodsEntity) {
        CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();

        cmsGoodsEntity.setPublish(1);

        // 描述
        if(!Strings.isNullOrEmpty(waldomCsvData.getPartDescription())){
            cmsGoodsEntity.setDescribe(waldomCsvData.getPartDescription());
        }

        // 购买类型0单个买1整包买
        cmsGoodsEntity.setPayType(0);

        // 最小起订
        cmsGoodsEntity.setMinimumOrder(Long.valueOf(waldomCsvData.getMoq()));

        // 增量
        cmsGoodsEntity.setIncremental(Long.valueOf(waldomCsvData.getSpq()));

        // mpq
        cmsGoodsEntity.setMpq(StringUtils.isEmpty(waldomCsvData.getMoq()) ? 1 : Long.parseLong(waldomCsvData.getMoq()));

        // 交货地区
        cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());

        // 是否需要3c认证
        cmsGoodsEntity.setCcc(WhetherOrNotEnum.NO.getCode());

        cmsGoodsEntity.setSales(0);
        cmsGoodsEntity.setClick(0);
        cmsGoodsEntity.setVisitor(0);

        JSONObject json = new JSONObject();

        String rohs = waldomCsvData.getRohs();
        String prc = waldomCsvData.getPrc();
        String coo = waldomCsvData.getCoo();
        String uom = waldomCsvData.getUom();
        String hts = waldomCsvData.getHts();

        if(!Strings.isNullOrEmpty(rohs)){
            json.put("ROHS", rohs);
        }

        if(!Strings.isNullOrEmpty(prc)){
            json.put("PRC", prc);
        }

        if(!Strings.isNullOrEmpty(coo)){
            json.put("COO", coo);
        }

        if(!Strings.isNullOrEmpty(uom)){
            json.put("UOM", uom);
        }

        if(!Strings.isNullOrEmpty(hts)){
            json.put("HTS", hts);
        }

        if(!json.isEmpty()){
            cmsGoodsEntity.setParams(json.toJSONString());
        }

        cmsGoodsEntity.setCreatedAt(DateUtils.now());
        cmsGoodsEntity.setUpdatedAt(DateUtils.now());

        cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
        cmsGoodsEntity.setSplName(SUPPLIER);
        cmsGoodsEntity.setBrandName(waldomCsvData.getManufacturerName());

        // 组装阶梯价格信息
        List<CmsPricesEntity> list = createCmsPrices(waldomCsvData, cmsGoodsEntity.getGoodid());
        cmsGoodsPojo.setCmsPricesEntityList(list);

        // 最小起订
        cmsGoodsEntity.setMinimumOrder(getMoqByLadderPriceList(cmsGoodsEntity.getMinimumOrder(), list));

        // 计算单价
        //cmsGoodsEntity.setUnitPrice(calculateUnitPrice(list));

        List<CmsPricesPojo> prices = new ArrayList<>();
        for(CmsPricesEntity cmsPricesEntity : list){
            CmsPricesPojo cmsPricesPojo = new CmsPricesPojo();
            BeanUtils.copyProperties(cmsPricesEntity, cmsPricesPojo);
            prices.add(cmsPricesPojo);
        }

        // 更新阶梯价格配置到商品表
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(prices, SerializerFeature.WriteMapNullValue));
        if(!jsonArray.isEmpty()){
            cmsGoodsEntity.setPrices(jsonArray.toString());
        }

        // 费率
        JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());

        // 从费率的json中获取信息补充到商品表实体中
        cmsGoodsEntity = addRateInfo(cmsGoodsEntity, data);

        cmsGoodsEntity.setHisp("waldom");

        // 封装
        cmsGoodsEntity.setPackage_(waldomCsvData.getPackageType());

        cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);

        // 组装商品表-副表信息
        cmsGoodsPojo.setCmsGoodsInformationEntity(createCmsGoodsInformation(cmsGoodsEntity.getGoodid(), cmsGoodsEntity.getInspectionChargesFee()));

        return cmsGoodsPojo;
    }

    /**
     * 组装阶梯价格信息
     * @param waldomCsvData Waldom数据解析
     * @param goodId 商品id
     */
    private List<CmsPricesEntity> createCmsPrices(WaldomCsvData waldomCsvData, String goodId) {
        List<CmsPricesEntity> result = new ArrayList<>();

        String priceBreakQty1 = waldomCsvData.getPriceBreakQty1();
        String priceBreak1 = waldomCsvData.getPriceBreak1();
        String priceBreakQty2 = waldomCsvData.getPriceBreakQty2();

        int position = 0;
        Long max;

        // 一级阶梯价格
        if(!Strings.isEmpty(priceBreakQty1) && !Strings.isEmpty(priceBreak1)){

            if(null != priceBreakQty2){
                max = Long.parseLong(priceBreakQty2) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.valueOf(priceBreakQty1), max, priceBreak1, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 二级阶梯价格
        String priceBreak2 = waldomCsvData.getPriceBreak2();
        String priceBreakQty3 = waldomCsvData.getPriceBreakQty3();
        if(!Strings.isEmpty(priceBreakQty2) && !Strings.isEmpty(priceBreak2)){

            if(null != priceBreakQty3){
                max = Long.parseLong(priceBreakQty3) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty2), max, priceBreak2, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 三级阶梯价格
        String priceBreak3 = waldomCsvData.getPriceBreak3();
        String priceBreakQty4 = waldomCsvData.getPriceBreakQty4();
        if(!Strings.isEmpty(priceBreakQty3) && !Strings.isEmpty(priceBreak3)){

            if(null != priceBreakQty4){
                max = Long.parseLong(priceBreakQty4) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty3), max, priceBreak3, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 四级阶梯价格
        String priceBreak4 = waldomCsvData.getPriceBreak4();
        String priceBreakQty5 = waldomCsvData.getPriceBreakQty5();
        if(!Strings.isEmpty(priceBreakQty4) && !Strings.isEmpty(priceBreak4)){

            if(null != priceBreakQty5){
                max = Long.parseLong(priceBreakQty5) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty4), max, priceBreak4, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 五级阶梯价格
        String priceBreak5 = waldomCsvData.getPriceBreak5();
        String priceBreakQty6 = waldomCsvData.getPriceBreakQty6();
        if(!Strings.isEmpty(priceBreakQty5) && !Strings.isEmpty(priceBreak5)){

            if(null != priceBreakQty6){
                max = Long.parseLong(priceBreakQty6) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty5), max, priceBreak5, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 六级阶梯价格
        String priceBreak6 = waldomCsvData.getPriceBreak6();
        String priceBreakQty7 = waldomCsvData.getPriceBreakQty7();
        if(!Strings.isEmpty(priceBreakQty6) && !Strings.isEmpty(priceBreak6)){

            if(null != priceBreakQty7){
                max = Long.parseLong(priceBreakQty7) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty6), max, priceBreak6, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 七级阶梯价格
        String priceBreak7 = waldomCsvData.getPriceBreak7();
        String priceBreakQty8 = waldomCsvData.getPriceBreakQty8();
        if(!Strings.isEmpty(priceBreakQty7) && !Strings.isEmpty(priceBreak7)){

            if(null != priceBreakQty8){
                max = Long.parseLong(priceBreakQty8) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty7), max, priceBreak7, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 八级阶梯价格
        String priceBreak8 = waldomCsvData.getPriceBreak8();
        String priceBreakQty9 = waldomCsvData.getPriceBreakQty9();
        if(!Strings.isEmpty(priceBreakQty8) && !Strings.isEmpty(priceBreak8)){

            if(null != priceBreakQty9){
                max = Long.parseLong(priceBreakQty9) - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty8), max, priceBreak8, CurrencyEnum.DOLLAR.getCode(), position));
            position = position + 1;
        }

        // 九级阶梯价格
        String priceBreak9 = waldomCsvData.getPriceBreak9();
        if(!Strings.isEmpty(priceBreakQty9) && !Strings.isEmpty(priceBreak9)){
            result.add(createCmsPriceData(goodId, Long.parseLong(priceBreakQty9), 0L, priceBreak9, CurrencyEnum.DOLLAR.getCode(), position));
        }

        return result;
    }

    /**
     * 生成批次号
     * @param dateCode dataCode
     * @param countryList 国家集合
     * @return 返回生成的批次号
     */
    private String createBatchData(String dateCode, List<String> countryList) {
        StringBuilder result = new StringBuilder();
        if(!Strings.isNullOrEmpty(dateCode)){
            String[] split = dateCode.split(";");
            if(split.length > 0){
                List<Integer> yearList = new ArrayList<>();
                List<BatchParamPojo> batchParamPojos = new ArrayList<>();
                for(String data : split){
                    String[] split1 = data.split("\\|");

                    // 数据中的国家
                    String dataCountry = split1[2].replaceAll(" ", "");

                    // 判断当前数据是否为当前国家的数据
                    boolean aBoolean = Boolean.FALSE;
                    for(String country : countryList){
                        if(dataCountry.equals(country)){
                            aBoolean = Boolean.TRUE;
                        }
                    }

                    if(!aBoolean){
                        continue;
                    }
                    BatchParamPojo batchParamPojo = new BatchParamPojo();
                    batchParamPojo.setCount(Integer.valueOf(split1[0].replaceAll(" ", "")));
                    String year = split1[1].replaceAll(" ", "").substring(split1[1].replaceAll(" ", "").length() - 2);
                    batchParamPojo.setYear(Integer.valueOf(year));
                    batchParamPojos.add(batchParamPojo);
                    yearList.add(Integer.valueOf(year));
                }

                if(yearList.size() > 0){
                    //去重
                    List<Integer> listNew = new ArrayList<Integer>(new TreeSet<Integer>(yearList));
                    for(Integer year : listNew){
                        StringBuilder sb = new StringBuilder();
                        Long count = 0L;
                        for (BatchParamPojo batchParamPojo : batchParamPojos){
                            if(batchParamPojo.getYear().intValue()== year.intValue()){
                                count += batchParamPojo.getCount();
                            }
                        }
                        sb.append(count).append(" 批号").append(year).append("+;");
                        result.append(sb.toString());
                    }
                }
            }
        }
        return result.toString();
    }
}